package com.coffee.middleware.dict.repository;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.coffee.core.CoffeeException;
import com.coffee.core.CoffeeResponseEnum;
import com.coffee.middleware.dict.entity.DictDataEntity;
import com.coffee.middleware.dict.repository.mapper.DictDataMapper;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.List;

/**
 * @author: songkui
 * @since: 2023/5/12 11:40
 */
@Service
public class DictDataRepository extends ServiceImpl<DictDataMapper, DictDataEntity> {

    public Integer saveDict(DictDataEntity entity){
        Assert.notNull(entity, "entity is null");
       if (checkExist(entity, false)){
           throw new CoffeeException(CoffeeResponseEnum.DataExist);
       }
       this.save(entity);
        return entity.getId();
    }
    public void updateDict(DictDataEntity entity){
        Assert.notNull(entity, "entity is null");
       if (checkExist(entity, true)){
           throw new CoffeeException(CoffeeResponseEnum.DataExist);
       }
       this.updateById(entity);
    }

    public List<DictDataEntity> listByType(Integer typeId){
        Assert.notNull(typeId, "type id is null");
        return this.lambdaQuery().eq(DictDataEntity::getTypeId, typeId).list();
    }

    /**
     * 检查是否存在
     * @param dataEntity
     * @param update
     * @return  true : exist
     */
    private boolean checkExist(DictDataEntity dataEntity, boolean update){
        List<DictDataEntity> list = listByType(dataEntity.getTypeId());
        if (CollectionUtil.isEmpty(list)){
            return false;
        }
        int count = 0;
        for (DictDataEntity entity : list){
            if (entity.getDictCode().equals(dataEntity.getDictCode())){
                ++ count;
            }
        }
        return update ? count > 1 : count > 0;
    }

}
